﻿#region Imports

using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using Spring.Data.NHibernate;
using Spring.Data.NHibernate.Generic.Support;
using d3PrtDgn.Data.IDAO;
using d3PrtDgn.Core.BaseData;
using d3PrtDgn.Data.Domain.Entity;

#endregion

namespace d3PrtDgn.Data.DAO
{
	/// <summary>
	/// Hibernate Photo DAO
	/// </summary>
    class PhotoDao : BaseDao, IPhotoDao
	{

		#region IPhotoDao members

		/// <summary>
		/// Saves or updates photo
		/// </summary>
		/// <param name="photo">Photo to save or update</param>
		/// <returns>Saved or updated photo</returns>
		public Photo SaveOrUpdate(Photo photo)
		{
            return base.SaveOrUpdate(photo) as Photo;
		}

		/// <summary>
		/// Deletes photo
		/// </summary>
		/// <param name="photo">Photo to delete</param>
		public void Delete(Photo photo)
		{
            base.Delete(photo);
		}

		/// <summary>
		/// Checks if photo abbreviation is unique in specified context
		/// </summary>
		/// <param name="abbreviation">Abbreviation to check</param>
		/// <param name="id">Allowed duplicate abbreviation ID</param>
		/// <returns>Flag if abbreviation is unique</returns>
		public bool IsUnique(string abbreviation, int id)
		{
			return
				HibernateTemplate.Find<Photo>("from Photo p where p.Abbreviation = ? and p.Id != ?", new object[] {abbreviation, id})
					.Count == 0;
		}

		/// <summary>
		/// Loads photo by abbreviation
		/// </summary>
		/// <param name="abbrev">Abbreviation</param>
		/// <param name="owner">Album owner</param>
		/// <returns>Loaded photo</returns>
		public Photo FindByAbbreviation(string abbrev, User owner)
		{
			IList<Photo> photos;
			if(owner != null)
			{
				photos =
					HibernateTemplate.Find<Photo>(
						"from Photo p where p.Abbreviation = ? and (p.Album.Owner.Id = ? or p.Album.Visibility = ?)",
						new object[] {abbrev, owner.Id, Visibility.Public});
			}
			else
			{
				photos = HibernateTemplate.Find<Photo>("from Photo p where p.Abbreviation = ?", abbrev);
			}

			if(photos.Count  == 0)
			{
				return null;
			}
			else
			{
				return photos[0];
			}
		}

		/// <summary>
		/// Loads photo by ID
		/// </summary>
		/// <param name="id">Photo ID</param>
		/// <returns>Loaded photo</returns>
		public Photo FindById(int id)
		{
			return HibernateTemplate.Get<Photo>(id);
		}

		#endregion
	}
}